package com.etc.common.util;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommDataParseUtils {
	/**
	 * 字节数组转为十六进制
	 * 
	 * @param readByte
	 * @return
	 */
	public static String transferToHex(byte[] readByte) {
		String res = "";
		for (int i = 0; i < readByte.length; i++) {
			String hex = Integer.toHexString(readByte[i] & 0xFF) + " ";
			if (hex.length() == 2) {
				hex = '0' + hex;
			}
			res = res + hex.toUpperCase();
		}
		return res;
	}

	/**
	 * 二进制转换为十六进制
	 * 
	 * @param bString
	 * @return
	 */
	public static String binaryString2hexString(String binaryString) {
		if (binaryString == null || binaryString.equals("")
				|| binaryString.length() % 8 != 0)
			return null;
		StringBuffer tmp = new StringBuffer();
		int iTmp = 0;
		for (int i = 0; i < binaryString.length(); i += 4) {
			iTmp = 0;
			for (int j = 0; j < 4; j++) {
				iTmp += Integer.parseInt(binaryString.substring(i + j, i + j
						+ 1)) << (4 - j - 1);
			}
			tmp.append(Integer.toHexString(iTmp));
		}
		return tmp.toString();
	}

	/**
	 * 十进制转换为十六进制(16bit)
	 * 
	 * @param decimalString
	 * @return
	 */
	public static String decimalString2hexString(String decimalString) {
		if (decimalString == null || decimalString.equals(""))
			return null;
		String hexString = Integer.toHexString(Integer.parseInt(decimalString));
		StringBuffer res = new StringBuffer();
		if (hexString.length() < 4) {
			for (int i = 1; i <= 4 - hexString.length(); i++) {
				res.append("0");
			}
		}
		res.append(hexString);
		res.insert(2, " ");
		return res.toString();
	}

	/**
	 * 计算效验和
	 * 
	 * @param hexString
	 * @return
	 */
	public static int calculateSum(String hexString) {
		String[] hexStringArray = hexString.split(" ");
		int efficacySum = 0;
		for (int i = 0; i < hexStringArray.length; i++) {
			efficacySum = efficacySum ^ Integer.parseInt(hexStringArray[i], 16);
		}
		return efficacySum;
	}

	/**
	 * 位数不够补零
	 * 
	 * @param length
	 * @param addString
	 * @param estimateString
	 */
	public static void addZero(int length, StringBuffer addString,
			String estimateString) {
		if (estimateString.length() < length) {
			for (int i = 1; i <= length - estimateString.length(); i++) {
				addString.append("0");
			}
		}
		addString.append(estimateString);
	}

	/**
	 * 获得有效字符信息
	 * 
	 * @param returnMessage
	 * @return
	 */
	public static String getMessage(String returnMessage) {
		System.out.println(returnMessage);
		int begin = returnMessage.indexOf("24");
		int end = returnMessage.indexOf("24", begin + 1);
		String message = returnMessage.substring(begin, end - 1);
		return message;
	}

	/**
	 * 将16进制数转换为汉字    
	 * 
	 * FIXME
	 * 
	 * @param content
	 * @return
	 */
	/*public static String hexStringToUnicode(String content) {
		String enUnicode = null;
		String deUnicode = null;
		for (int i = 0; i < content.length(); i++) {
			if (enUnicode == null) {
				enUnicode = String.valueOf(content.charAt(i));
			} else {
				enUnicode = enUnicode + content.charAt(i);
			}
			if (i % 4 == 3) {
				if (enUnicode != null) {
					if (deUnicode == null) {
						deUnicode = String
								.valueOf((char) Integer.valueOf(enUnicode, 16).intValue());
					} else {
						deUnicode = deUnicode
								+ String.valueOf((char) Integer.valueOf(enUnicode, 16).intValue());
					}
				}
				enUnicode = null;
			}
		}
		return deUnicode;
	}*/

	@SuppressWarnings("unused")
	public static String hexStringToUnicode(String str) {
		String[] split = str.split(" ");
		List<Integer> list = new ArrayList<Integer>(split.length);
		PipedInputStream pin = new PipedInputStream();
		PipedOutputStream pout = null;
		BufferedReader buf = null;
		StringBuffer result = new StringBuffer();
		try {
			pout = new PipedOutputStream(pin);
			for (String each : split) {
				list.add(Integer.parseInt(each, 16));
			}
			// 管道的一端 写入
			for (int each : list) {
				pout.write(each);
			}
			pout.flush();
			pout.close();
			// 管道的另一端读取
			buf = new BufferedReader(new InputStreamReader(pin));
			char[] cbuf = new char[128];
			int i;
			while ((i = buf.read(cbuf)) != -1) {
				for(char ch : cbuf){
					if(ch != '\0'){
						result.append(ch);
					}
				}
			}
			pin.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	
	/**
	 * 将汉字转换为16进制数
	 * 
	 * @param content
	 * @return
	 */
	private static String hexString = "0123456789ABCDEF";
	public static String unicodeToHexString(String str) {
		byte[] bytes = str.getBytes();
		StringBuilder sb= new StringBuilder(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			sb.append(" ");
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	/**
	 * 十六进制转字符
	 * 
	 * @param hexString
	 * @return
	 */
	public static String hexStringToChar(String hexString) {
		String[] hexArray = hexString.split(" ");
		String res = "";
		for (String hex : hexArray) {
			res += (char) Integer.parseInt(hex, 16);
		}
		return res;
	}

	/**
	 * 字符转十六进制
	 * 
	 * @param content
	 * @return
	 */
	public static String charToHexString(String content) {
		String hexString = "";
		for (int i = 0; i < content.length(); i++) {
			if (i < content.length() - 1) {

				hexString += Integer.toHexString(content.charAt(i))
						.toUpperCase() + " ";
			} else {
				hexString += Integer.toHexString(content.charAt(i))
						.toUpperCase();
			}
		}
		return hexString;
	}

	/**
	 * 十六进制信息转十进制数字 (十六进制信息包含空格)
	 * 
	 * @param hexString
	 * @return
	 */
	public static String hexStringToDecimal(String hexString) {
		//
		hexString = hexString.replace(" ", "");
		String decimal = Integer.parseInt(hexString, 16) + "";
		return decimal;
	}

	/**
	 * 十六进制（含空格）转十进制年份
	 * 
	 * @param hexString
	 * @return
	 */
	public static String hexStringToYear(String hexString) {
		String decimal = "";
		String[] hexArray = hexString.split(" ");
		for (String hex : hexArray) {
			decimal += Integer.parseInt(hex, 16);
		}
		return decimal;
	}

	/**
	 * 字符串不为空
	 * 
	 * @param checkString
	 * @return
	 */
	public static boolean isNotBlank(String checkString) {
		boolean res = false;
		if (checkString != null && !checkString.equals("")
				&& !checkString.equals(" ")) {
			res = true;
		}
		return res;
	}

	/**
	 * 十进制转换为十六进制卡号(32bit)
	 * 
	 * @param decimalString
	 * @return
	 */
	public static String getHexStringCardId(String decimalString) {
		if (decimalString == null || decimalString.equals(""))
			return null;
		String hexString = Integer.toHexString(Integer.parseInt(decimalString))
				.toUpperCase();
		StringBuffer res = new StringBuffer();
		if (hexString.length() < 6) {
			for (int i = 1; i <= 6 - hexString.length(); i++) {
				res.append("0");
			}
		}
		res.append(hexString);
		res.insert(2, " ");
		res.insert(5, " ");
		return res.toString();
	}
	
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	/**
	 * 16进制转字符串
	 * @param hex
	 * @return
	 */
	public static String hexToString(String hex) {
		hex = hex.replaceAll(" ", "");
		String digital = "0123456789ABCDEF";
		char[] hex2char = hex.toCharArray();
		byte[] bytes = new byte[hex.length() / 2];
		int temp;
		for (int i = 0; i < bytes.length; i++) {
			temp = digital.indexOf(hex2char[2 * i]) * 16;
			temp += digital.indexOf(hex2char[2 * i + 1]);
			bytes[i] = (byte) (temp & 0xff);
		}
		String str = new String(bytes);
		return str;
	}
	/**
	 * 字符串转16进制
	 * @param bin
	 * @return
	 */
	public static String StringTohex(String bin) {
		char[] digital = "0123456789ABCDEF".toCharArray();
		StringBuffer sb = new StringBuffer("");
		byte[] bs = bin.getBytes();
		int bit;
		for (int i = 0; i < bs.length; i++) {
			sb.append(" ");
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(digital[bit]);
			bit = bs[i] & 0x0f;
			sb.append(digital[bit]);
		}
		return sb.toString();
	}
	
	/**
	 * 验证消息长度是否一致
	 * @param message 原消息
	 * @param messageLength 消息长度
	 * @return
	 */
	public static boolean isMessageLength(String message, String messageLength){
		boolean res = false;
		message = "24 " + message;
		// 获得消息长度值
		String length = message.split(" ").length + "";
		if(messageLength.equals(length)){
			res = true;
		}
		return res;
	}
	
	/**
	 * 验证校验和是否正确
	 * @param message 原消息
	 * @param checkSum 校验和
	 * @return
	 */
	public static boolean isCheckSum(String message, String checkSum){
		boolean res = false;
		message = "24 " + message;
		// 获得校验和
		String sum = calculateSum(message.substring(0, message.length() - 2)) + "";
		if(checkSum.equals(sum)){
			res = true;
		}
		return res;
	}
	
	/**
	 * 返回消息头list
	 * @return
	 */
	public static List<String> getContentTitle(){
		List<String> titleList = new ArrayList<String>();
		titleList.add("24 54 58 58 58");
		titleList.add("24 44 57 58 58");
		titleList.add("24 46 4B 58 58");
		titleList.add("24 5A 4A 58 58");
		titleList.add("24 53 4A 58 58");
		titleList.add("24 49 43 58 58");
		titleList.add("24 42 42 58 58");
		return titleList;
	}
}
